﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MuaChung.Models;
using MuaChung.Base;
using System.Runtime.Serialization.Formatters.Soap;
using System.Xml.Serialization;
using System.IO;
using MuaChung.doanhnghiepbiz;
using System.Xml;
using System.Text;
using MuaChung.NganHang5D;

namespace MuaChung.Controllers
{
    public class ServiceController : Controller
    {
        //
        // GET: /Service/

        public ActionResult Index()
        {
            return View();
        }

        [Authorize(Roles="Admin")]
        public ActionResult WSLogin()
        {
            return View();
        }

        [HttpPost]
        [Authorize(Roles="Admin")]
        public ActionResult WSLogin(WSLogonModel model, FormCollection frm)
        {            
            
            return View(model);
        }

        [Authorize(Roles = "Admin")]
        public ActionResult AddNewService()
        {
            WSDynamicModel model = new WSDynamicModel();            
            ViewData["status"] = "Fail";
            return View(model);
        }

        [HttpPost]
        [Authorize(Roles="Admin")]
        public ActionResult AddNewService(WSDynamicModel model, FormCollection frm)
        {

            string status = string.Empty;
            try
            {
                WebServiceInvoker ws = new WebServiceInvoker(new Uri(model.serviceURL));
                ServiceModel.currentWS.serviceURL = model.serviceURL;
                ServiceModel.currentWS.services = new List<Service_Methods>();
                List<string> serviceNames = ws.AvailableServices;
                foreach (var item in serviceNames)
                {
                    Service_Methods tmp = new Service_Methods();
                    tmp.serviceName = item;
                    tmp.serviceMethods = ws.EnumerateServiceMethods(item);
                    ServiceModel.currentWS.services.Add(tmp);
                }
                ViewData["Message"] = "Webservice OK!";
                ViewData["status"] = "OK";
                status = "OK";
                if (ServiceModel.FindWSByURL(model.serviceURL) != null)
                {
                    status = "Exist";
                    ViewData["Message"] = "Dịch vụ này đã tồn tại!";
                    model.doanhNghiep = ServiceModel.FindWSByURL(model.serviceURL).DOANHNGHIEP;
                    return View(model);
                }
            }
            catch
            {
                ViewData["Message"] = "Webservice Error, please check the url!";
                ViewData["status"] = "Fail";
                status = "Fail";
            }
            if (frm.AllKeys[2] == "check")
            {
                if (status == "Fail")
                {
                    return View(model);
                }
            }
            else if (frm.AllKeys[4] == "addNew")
            {
                string name = frm.GetValue("Ten").AttemptedValue;
                string diachi = frm.GetValue("DiaChi").AttemptedValue;
                string dt = frm.GetValue("DienThoai").AttemptedValue;
                string web = frm.GetValue("web").AttemptedValue;                
                DOANHNGHIEP tmp = new DOANHNGHIEP();
                tmp.Ten_DoanhNghiep = name;
                tmp.DiaChi = diachi;              
                tmp.WebSite = web;
                if (DoanhNghiepModel.AddDoanhNghiep(tmp))
                {
                    ViewData["Message"] = "Thêm doanh nghiệp thành công!";
                }
                else
                {
                    ViewData["Message"] = "Thêm doanh nghiệp thất bại!";
                }
            }
            else if (frm.AllKeys[6] == "add")            
            {
                if (status != "OK")
                {
                    return View(model);
                }
                string dnID = frm.GetValue("SelectDoanhNghiep").AttemptedValue;
                string type = frm.GetValue("type").AttemptedValue;
                string name = frm.GetValue("WSName").AttemptedValue;
                string usrname = frm.GetValue("wsusrname").AttemptedValue;
                string pass = frm.GetValue("wspass").AttemptedValue;
                if (name == "" || usrname == "" || pass == "")
                {
                    ViewData["Message"] = "Thông tin chưa đầy đủ, vui lòng điền đầy đủ thông tin và thử lại lần nữa!";
                    return View(model);
                }
                WEBSERVICE wstmp = new WEBSERVICE();
                wstmp.URL = model.serviceURL;
                wstmp.Ma_DoanhNghiep = Convert.ToInt32(dnID);
                wstmp.Ten = name;
                wstmp.WSUSERNAME = usrname;
                wstmp.WSPASSWORD = pass;
                switch (type)
                {
                    case "biz":
                        {
                            wstmp.LoaiWS = "biz";
                            
                            break;
                        }
                    case "vanchuyen":
                        {
                            wstmp.LoaiWS = "vanchuyen";
                            break;
                        }
                    case "nganhang":
                        {
                            wstmp.LoaiWS = "nganhang";
                            break;
                        }
                    default:
                        break;
                }
                if (ServiceModel.AddWS(wstmp))
                {
                    ViewData["Message"] = "Thêm dịch vụ thành công!";
                }
            }
            return View(model);
        }

        [Authorize(Roles = "Admin")]
        public ActionResult GetServicesNames()
        {
            List<string> model = new List<string>();            
            foreach (var item in ServiceModel.currentWS.services)
            {
                model.Add(item.serviceName);
            }
            return View(model);
        }

        [Authorize(Roles = "Admin")]
        public ActionResult GetMethods(int sid)
        {
            List<string> model = new List<string>();
            foreach (var item in ServiceModel.currentWS.services[sid].serviceMethods)
            {
                model.Add(item);
            }
            return View(model);            
        }

        public ActionResult SelectWSCoupon(string type)
        {
            List<WEBSERVICE> model = new List<WEBSERVICE>();
            model = ServiceModel.GetAllWSByType(type);
            return View(model);
        }

        [Authorize(Roles = "Admin")]
        public ActionResult GetListCoupon()
        {
            List<CouponView> model = new List<CouponView>();
            ViewData["status"] = "Error";
            ViewData["wsID"] = "";
            return View(model);
        }        

        [HttpPost]
        [Authorize(Roles="Admin")]
        public ActionResult GetListCoupon(FormCollection frm)
        {
            List<CouponView> model = new List<CouponView>();
            List<Coupon> lstcp = new List<Coupon>();
            int wsID = Convert.ToInt32(frm.GetValue("SelectWSCoupon").AttemptedValue);
            ViewData["wsID"] = wsID;
            try
            {
                lstcp = ServiceModel.GetListCoupon(ServiceModel.FindWSByID(wsID));
                ServiceModel.lstTmpCoupons = lstcp;
                if (model == null)
                {
                    ViewData["Message"] = "Không thể kết nối đến webservice!";
                    ViewData["Status"] = "Error";
                    return View(model);
                }
                else
                {
                    foreach (var item in lstcp)
                    {
                        CouponView tmp = new CouponView();
                        if (CouponModel.FindByMaCoupon(item.MaCoupon) != null)
                        {
                            tmp.status = 1;
                        }
                        else
                        {
                            tmp.status = 0;
                        }
                        tmp.cp = item;
                        model.Add(tmp);
                    }
                }

                //WEBSERVICE wsc = ServiceModel.FindWSByID(wsID);
                //WebServiceInvoker wsi = new WebServiceInvoker(new Uri("http://www.beatifulhousews.somee.com/Service1.asmx"));
                //string serviceName = wsi.AvailableServices[0];
                //string[] args = new string[] { "khtn", "123456" };
                //string sid = wsi.InvokeMethod<string>(serviceName, "Authenticate", args);

                //Coupon[] lstObj = wsi.InvokeMethod<Coupon[]>(serviceName, "FindAllCoupons", new object[] { sid });
                //object[] lstObj = wsi.InvokeMethod<object[]>(serviceName, "FindAllCoupons", new object[] { sid });
                
                //Coupon[] lst = wsi.GetCoupon(serviceName, "FindAllCoupons", new object[] { sid });

                //string FilePath = BaseWeb.RootServerPath + "Content/" + sid + ".ex";
                ////System.IO.File.Create(FilePath);

                //List<Coupon> lstCoupons = new List<Coupon>();
                //foreach (var item in lstObj)
                //{
                //    try
                //    {
                //        Coupon tmp = new Coupon();
                //        String XmlizedString = null;
                //        MemoryStream memoryStream = new MemoryStream();
                //        XmlSerializer xs = new XmlSerializer(item.GetType());
                //        XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
                //        xs.Serialize(xmlTextWriter, item);
                //        memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
                //        XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
                //        //deserialization
                //        XmlSerializer xs2 = new XmlSerializer(typeof(Coupon));
                //        MemoryStream memoryStream2 = new MemoryStream(StringToUTF8ByteArray(XmlizedString));
                //        XmlTextWriter xmlTextWriter2 = new XmlTextWriter(memoryStream2, Encoding.UTF8);
                //        object x = xs2.Deserialize(memoryStream2);
                //        //tmp = (Coupon)xs2.Deserialize(memoryStream2);
                //        lstCoupons.Add(tmp);
                //    }
                //    catch (Exception e)
                //    {
                //        System.Console.WriteLine(e);
                //        return null;
                //    }
                //}               
            }
            catch
            {
                ViewData["status"] = "Error";
                ViewData["Message"] = "Không thể kết nối đến webservice!";
                return View(model);
            }
            if (model.Count == 0)
            {
                ViewData["status"] = "Empty";
            }
            else
            {
                ViewData["status"] = "OK";
            }

            return View(model);
        }

        [Authorize(Roles = "Admin")]
        public ActionResult ListAllService()
        {
            List<WEBSERVICE> model = new List<WEBSERVICE>();
            model = ServiceModel.GetAllWS();
            return View(model);
        }

        [Authorize(Roles = "Admin")]
        public ActionResult EditService(int id)
        {
            WEBSERVICE model = ServiceModel.FindWSByID(id);
            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Admin")]
        public ActionResult EditService(WEBSERVICE model, FormCollection frm)
        {
            model.Ma_DoanhNghiep = Convert.ToInt32(frm.GetValue("SelectDoanhNghiep").AttemptedValue);            
            return View(model);
        }

        [Authorize(Roles = "Admin")]
        public ActionResult RegisterCoupon(FormCollection frm)
        {
            int wsID = Convert.ToInt32(frm.GetValue("wsID").AttemptedValue);
            List<string> lstMa = new List<string>();
            for (int i = 1; i < frm.AllKeys.Count(); i++)
            {
                lstMa.Add(frm.AllKeys[i]);
            }
            List<RegisterCouponModel> model = ServiceModel.RegisterCoupon(ServiceModel.FindWSByID(wsID),lstMa);
            foreach (var item in model)
            {
                if (item.status)
                {
                    Coupon n = ServiceModel.FindTmpCoupon(item.maCoupon);
                    CouponModel.AddRegisteredCoupon(n, wsID);
                }
            }
            return View(model);
        }
        
    }
}
